<!--created by yuyupeng-->
<!--2023/03/22-->
<!-- 数据字典管理-->
<template>
  <div class="list-card-container">
    <a-card title="数据字典管理" class="general-card">
      <!-- 查询表单 -->
      <AdvancedSearch
        ref="searchRef"
        :data-source="searchItemList"
        @change="searchByParams"
      />
      <a-space style="margin-top: 5px; margin-bottom: 5px">
        <AdvancedDrawer
          click="button"
          title="新增数据字典信息"
          clickword="新增数据字典"
          :narrow="true"
          :rules="advancedDrawerRules"
          :data-source="addDrawerConfig"
          @change="addDrawerSubmit"
        />
        <a-popconfirm
          content="确定删除吗?"
          type="warning"
          @ok="deleteTbDataList(selectedKeys)"
        >
          <a-button :disabled="selectedKeys.length === 0"
            ><icon-delete />批量删除</a-button
          >
        </a-popconfirm>
      </a-space>
      <!-- 表格 -->
      <a-table
        v-model:selectedKeys="selectedKeys"
        row-key="id"
        column-resizable
        :columns="tbCols"
        :data="tbData"
        :row-selection="rowSelection"
        :pagination="pagination"
        :loading="tbLoading"
        :scroll="{ x: '100%', y: 600 }"
        :scrollbar="true"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 插槽-数据字典详情 -->
        <template #type="{ record }">
          <a-link type="text" @click="showDetailDrawer(record)">
            {{ record.type }}
          </a-link>
        </template>
        <!-- 插槽-一键复制 -->
        <template #quickCopyToolTip="{ record, column }">
          <quick-copy-tool-tip
            :show-text="record[column['dataIndex']]"
            show-btn
          />
        </template>
        <!-- 插槽-操作 -->
        <template #operation="{ record }">
          <a-space>
            <a-link type="text" @click="showEditDrawer(record)"> 修改 </a-link>
            <a-popconfirm
              content="确定删除吗?"
              type="warning"
              @ok="deleteTbData(record.id)"
            >
              <a-link type="text">删除</a-link>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 数据字典详情 -->
    <AdvancedDrawer
      ref="dictDataDrawerRef"
      click="link"
      title="数据字典详情"
      clickword=""
      :data-source="dictDataDrawerConfig"
      :data-record="currentRecord"
    >
      <template #dictData>
        <DictData :dict-type="currentRecord?.type || ''" />
      </template>
    </AdvancedDrawer>
    <!-- 修改抽屉 -->
    <AdvancedDrawer
      ref="editDrawerRef"
      click="link"
      title="修改数据字典信息"
      clickword=""
      :narrow="true"
      :rules="advancedDrawerRules"
      :data-source="editDrawerConfig"
      :data-record="currentRecord"
      @change="editDrawerSubmit"
    />
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import {
    Notification,
    TableColumnData,
    TableRowSelection,
  } from '@arco-design/web-vue';
  import {
    DictTypeRecord,
    DictTypeParams,
  } from '@/api/system/model/dictTypeModel';
  import {
    queryDictTypeRecordList,
    addDictTypeRecord,
    editDictTypeRecord,
    deleteDictTypeRecords,
  } from '@/api/system/dictionary';
  import { ref, onMounted, reactive } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  import DictData from '@/views/system/dictionary/components/dict-data.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';

  /**
   * data
   */
  // 表格
  const tbData = ref<DictTypeRecord[]>([]);
  const tbCols: TableColumnData[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    /* { title: '字典主键', dataIndex: 'id', fixed: 'left', ellipsis: true, align: 'center', tooltip: true }, */
    {
      title: '字典类型名称',
      dataIndex: 'name',
      width: 150,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '字典类型编码',
      align: 'center',
      width: 150,
      slotName: 'type',
    },
    /* { title: '状态（0正常 1停用）', dataIndex: 'status', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' }, */
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    /* { title: '所属部门ID(非必须)', dataIndex: 'deptId', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '所属组织机构ID(非必须)', dataIndex: 'orgId', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '创建者', dataIndex: 'creator', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' }, */
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    /* { title: '更新者', dataIndex: 'updater', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新时间', dataIndex: 'updateTime', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新ip', dataIndex: 'updateIp', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '是否删除(非必须)', dataIndex: 'deleted', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', dataIndex: 'secretLevel', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '乐观锁', dataIndex: 'version', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' }, */
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 120,
      slotName: 'operation',
    },
  ];
  const searchRef = ref<any>();
  const dictDataDrawerRef = ref<any>();
  const editDrawerRef = ref<any>();
  const currentRecord = ref<DictTypeRecord>(); // 记录当前选择的表格行
  const tbLoading = ref<boolean>(false);
  // 勾选框
  const selectedKeys = ref([]);
  const rowSelection: TableRowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    // { type: 'text', labelText: '字典主键', fieldName: 'id'},
    { type: 'text', labelText: '字典类型名称', fieldName: 'name' },
    { type: 'text', labelText: '字典类型编码', fieldName: 'type' },
    /* {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    },
    { type: 'text', labelText: '备注', fieldName: 'remark'},
    { type: 'text', labelText: '所属部门ID(非必须)', fieldName: 'deptId'},
    { type: 'text', labelText: '所属组织机构ID(非必须)', fieldName: 'orgId'},
    { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
  ];
  // 新增抽屉配置项
  const addDrawerConfig = [
    // { type: 'text', labelText: '字典主键', fieldName: 'id'},
    { col: 24, type: 'text', labelText: '字典类型名称', fieldName: 'name' },
    { col: 24, type: 'text', labelText: '字典类型编码', fieldName: 'type' },
    /* {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    }, */
    { col: 24, type: 'text', labelText: '备注', fieldName: 'remark' },
    /* { type: 'text', labelText: '所属部门ID(非必须)', fieldName: 'deptId'},
    { type: 'text', labelText: '所属组织机构ID(非必须)', fieldName: 'orgId'},
    { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
  ];
  // 修改抽屉配置项
  const editDrawerConfig = [
    {
      col: 24,
      type: 'text',
      labelText: '字典主键',
      fieldName: 'id',
      visible: false,
    },
    { col: 24, type: 'text', labelText: '字典类型名称', fieldName: 'name' },
    {
      col: 24,
      type: 'text',
      labelText: '字典类型编码',
      fieldName: 'type',
      disabled: true,
    },
    /* {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    }, */
    { col: 24, type: 'text', labelText: '备注', fieldName: 'remark' },
    /* { type: 'text', labelText: '所属部门ID(非必须)', fieldName: 'deptId'},
    { type: 'text', labelText: '所属组织机构ID(非必须)', fieldName: 'orgId'},
    { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
  ];
  // 抽屉表单项校验配置
  const advancedDrawerRules = ref({
    type: [{ required: true, message: '请输入数据字典编码' }],
    name: [{ required: true, message: '请输入数据字典类型名称' }],
  });
  // 数据字典详情抽屉配置项
  const dictDataDrawerConfig = [
    {
      col: 24,
      type: 'other',
      labelText: '',
      fieldName: 'dictData',
    },
  ];
  /**
   * func
   */
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbDataByPage = async (reqdata: any = {}) => {
    const params: DictTypeParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...reqdata,
    };
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const { data } = await queryDictTypeRecordList(params);
      tbData.value = data.list;
      pagination.total = Number(data.total); // 用Number函数转一下，否则f12控制台会有警告，很不好看
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    getTbDataByPage(reqdata);
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    console.log(pageSize);
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 新增抽屉提交
   */
  const addDrawerSubmit = async (reqdata: any) => {
    try {
      const res = (await addDictTypeRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '保存成功！',
        });
      } else {
        Notification.error({
          title: '保存失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 修改抽屉提交
   */
  const editDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    try {
      const res = (await editDictTypeRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 删除数据字典信息
   */
  const deleteTbData = async (id: string) => {
    const reqdata = [];
    reqdata.push(id);
    try {
      const res = (await deleteDictTypeRecords(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 批量删除数据字典信息，传id数组，支持批量
   */
  const deleteTbDataList = async (ids: string[]) => {
    try {
      const res = (await deleteDictTypeRecords(ids)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 打开详情抽屉
   * @param record 当前选择的表格行数据
   */
  const showDetailDrawer = (record: DictTypeRecord) => {
    currentRecord.value = record;
    dictDataDrawerRef.value.showDrawer(); // 打开数据字典详情抽屉
  };
  /**
   * @description 打开修改抽屉
   * @param record 当前选择的表格行数据
   */
  const showEditDrawer = (record: DictTypeRecord) => {
    currentRecord.value = record;
    editDrawerRef.value.showDrawer(); // 打开修改抽屉
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTbDataByPage();
  });
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    // background-color: var(--color-bg-1);
    border-radius: var(--border-radius-default);
  }
</style>
